import 'package:flutter/foundation.dart';
import 'dart:convert';
import '../models/weight_record.dart';
import '../services/cache_service.dart';
import '../utils/bmi_calculator.dart';

class WeightManagementProvider with ChangeNotifier {
  List<WeightRecord> _weightRecords = [];
  double? _height; // 身高(cm)
  final CacheService _cacheService = CacheService();
  static const String _recordsKey = 'weight_records';
  static const String _heightKey = 'user_height';

  List<WeightRecord> get weightRecords => _weightRecords;
  double? get height => _height;

  // 获取最新记录
  WeightRecord? get latestRecord =>
      _weightRecords.isNotEmpty ? _weightRecords.first : null;

  // 获取体重变化趋势
  double get weightChangeTrend {
    if (_weightRecords.length < 2) return 0;
    return _weightRecords.first.weight - _weightRecords[1].weight;
  }

  WeightManagementProvider() {
    _loadData();
  }

  Future<void> _loadData() async {
    await _loadHeight();
    await _loadWeightRecords();
  }

  Future<void> _loadHeight() async {
    final heightData = await _cacheService.getData(_heightKey);
    if (heightData != null) {
      _height = double.parse(heightData.toString());
      notifyListeners();
    }
  }

  Future<void> setHeight(double height) async {
    _height = height;
    await _cacheService.saveData(_heightKey, height.toString());

    // 更新BMI值
    if (_weightRecords.isNotEmpty) {
      _updateBMIValues();
      await _saveWeightRecords();
    }

    notifyListeners();
  }

  void _updateBMIValues() {
    if (_height == null) return;

    for (var i = 0; i < _weightRecords.length; i++) {
      final record = _weightRecords[i];
      final bmi = BMICalculator.calculateBMI(record.weight, _height!);

      _weightRecords[i] = WeightRecord(
        id: record.id,
        weight: record.weight,
        waistCircumference: record.waistCircumference,
        bmi: bmi,
        bodyFatPercentage: record.bodyFatPercentage,
        recordTime: record.recordTime,
        notes: record.notes,
      );
    }
  }

  Future<void> _loadWeightRecords() async {
    final data = await _cacheService.getData(_recordsKey);
    if (data != null) {
      try {
        _weightRecords = List<WeightRecord>.from(
          (data as List).map((item) => WeightRecord.fromJson(item)),
        );

        // 按时间排序（最新的在前）
        _weightRecords.sort((a, b) => b.recordTime.compareTo(a.recordTime));

        notifyListeners();
      } catch (e) {
        print('加载体重记录失败: $e');
      }
    }
  }

  Future<void> _saveWeightRecords() async {
    final jsonData = _weightRecords.map((record) => record.toJson()).toList();
    await _cacheService.saveData(_recordsKey, jsonData);
  }

  Future<void> addWeightRecord(WeightRecord record) async {
    // 插入并保持时间倒序
    _weightRecords.insert(0, record);
    notifyListeners();
    await _saveWeightRecords();
  }

  Future<void> updateWeightRecord(WeightRecord updatedRecord) async {
    final index = _weightRecords.indexWhere((r) => r.id == updatedRecord.id);
    if (index >= 0) {
      _weightRecords[index] = updatedRecord;

      // 重新排序以确保时间顺序
      _weightRecords.sort((a, b) => b.recordTime.compareTo(a.recordTime));

      notifyListeners();
      await _saveWeightRecords();
    }
  }

  Future<void> deleteWeightRecord(String id) async {
    _weightRecords.removeWhere((record) => record.id == id);
    notifyListeners();
    await _saveWeightRecords();
  }
}
